<template>
	<el-container class="friend-page">
		<el-aside width="280px" class="friend-list-box">
			<div class="friend-list-header">
				<div class="search-container">
					<el-input class="search-input" placeholder="搜索好友" v-model="searchText">
						<template #prefix>
							<el-icon><Search /></el-icon>
						</template>
					</el-input>
					<el-button 
						class="add-friend-btn"
						type="danger"
						circle
						@click="onShowAddFriend()" 
						title="添加好友">
						<el-icon><Plus /></el-icon>
					</el-button>
					<add-friend :dialogVisible="showAddFriend" @close="onCloseAddFriend" @refresh-friends="refreshFriendList"></add-friend>
				</div>
			</div>
			
			<el-scrollbar class="friend-list-items" ref="scrollbar" v-on:scroll.native="handleScroll">
				<div class="friend-list-container" v-loading="initialLoading" element-loading-text="加载中...">
					<friend-apply-list @refresh-friend-list="refreshFriendList"></friend-apply-list>
					<div v-for="(friend,index) in displayList" :key="index" class="friend-item-wrapper">
						<friend-item v-show="friend.nickName.includes(searchText)" :index="index"
							:active="friend === $store.state.friendStore.activeFriend" @chat="onSendMessage(friend)"
							@delete="onDelItem(friend,index)" @click.native="onActiveItem(friend,index)">
						</friend-item>
					</div>
					<div v-if="loading" class="loading-more">
						<el-icon class="loading-icon"><Loading /></el-icon>
						<span>加载中...</span>
					</div>
					<div v-if="!loading && displayList.length === 0" class="empty-tip">
						<el-empty description="暂无好友" :image-size="120">
							<el-button type="danger" @click="onShowAddFriend()">添加好友</el-button>
						</el-empty>
					</div>
				</div>
			</el-scrollbar>
		</el-aside>
		<el-container class="friend-box">
			<div class="friend-header" v-show="userInfo.id">
				{{userInfo.nickName}}
			</div>
			<div v-show="userInfo.id">
				<div class="friend-detail">
					<head-image :size="120" :name="userInfo.nickName" :url="userInfo.headImage"
						@click.native="showFullImage()" radius="10%"></head-image>
					<div class="info-container">
						<el-descriptions 
							:column="1" 
							border
							:labelStyle="{
								width: '80px',
								'text-align': 'right',
								'background-color': '#f5f7fa'
							}"
							:contentStyle="{
								'padding-left': '20px'
							}">
							<template #title>
								<div class="friend-title">
									<span class="nickname">{{userInfo.nickName}}</span>
									<el-tag size="small" type="success" v-if="userInfo.online">在线</el-tag>
									<el-tag size="small" type="info" v-else>离线</el-tag>
								</div>
							</template>
							<el-descriptions-item label="ID">{{userInfo.chatNo}}</el-descriptions-item>
							<el-descriptions-item label="备注">
								<div class="remark-wrapper">
									<span v-if="!isEditing">{{ userInfo.userName || '暂无备注' }}</span>
									<el-icon v-if="!isEditing" class="edit-icon" @click="startEdit"><Edit /></el-icon>
									<div v-else class="edit-form">
										<el-input
											v-model="editingRemarkName"
											size="small"
											placeholder="请输入备注名"
										></el-input>
										<div class="btn-group">
											<el-button 
												type="danger" 
												size="small"
												@click="saveRemarkName">
												确定
											</el-button>
											<el-button 
												size="small"
												@click="cancelEdit">
												取消
											</el-button>
										</div>
									</div>
								</div>
							</el-descriptions-item>
							<el-descriptions-item label="性别">{{ userInfo.sex == 0 ? "男" : "女" }}</el-descriptions-item>
							<el-descriptions-item label="签名">{{ userInfo.signature || '这个人很懒，什么都没写~' }}</el-descriptions-item>
						</el-descriptions>
						
						<div class="friend-btn-group">
							<el-button v-show="isFriend" type="danger" @click="onSendMessage(userInfo)">
								<el-icon><ChatDotRound /></el-icon>
								发消息
							</el-button>
							<el-button v-show="!isFriend" type="danger" @click="onAddFriend(userInfo)">
								<el-icon><Plus /></el-icon>
								添加好友
							</el-button>
							<el-button v-show="isFriend" type="danger" @click="onDelItem(userInfo,activeIdx)">
								<el-icon><Delete /></el-icon>
								删除好友
							</el-button>
						</div>
					</div>
				</div>
				<el-divider content-position="center"></el-divider>
			</div>
		</el-container>
	</el-container>
</template>

<script>
	import FriendItem from "../components/friend/FriendItem.vue";
	import AddFriend from "../components/friend/AddFriend.vue";
	import FriendApplyList from "../components/friend/FriendApplyList.vue";
	import HeadImage from "../components/common/HeadImage.vue";

	export default {
		name: "friend",
		components: {
			FriendItem,
			AddFriend,
			FriendApplyList,
			HeadImage,
		},
		data() {
			return {
				searchText: "",
				showAddFriend: false,
				activeIdx: -1,
				userInfo: {},
				dataList: [],
				total: 0,
				currentPage: 1,
				pageSize: 20,
				loading: false,
				displayList: [],
				isEditing: false,
				editingRemarkName: '',
				remarkName: '',
				initialLoading: true,
				activeTab: 'friends'
			}
		},
		created() {
			this.loadInitialData();
		},
		mounted() {
			this.$nextTick(() => {
				const scrollbar = this.$refs.scrollbar;
				if (scrollbar) {
					const scrollWrapper = scrollbar.$el.querySelector('.el-scrollbar__wrap');
					if (scrollWrapper) {
						scrollWrapper.addEventListener('scroll', this.handleScroll);
					}
				}
			});
		},
		beforeDestroy() {
			const scrollbar = this.$refs.scrollbar;
			if (scrollbar) {
				const scrollWrapper = scrollbar.$el.querySelector('.el-scrollbar__wrap');
				if (scrollWrapper) {
					scrollWrapper.removeEventListener('scroll', this.handleScroll);
				}
			}
		},
		methods: {
			loadInitialData() {
				this.initialLoading = true;
				this.displayList = this.friendList.slice(0, this.pageSize);
				this.$nextTick(() => {
					setTimeout(() => {
						this.initialLoading = false;
					}, 500);
				});
			},
			handleScroll(e) {
				if (!e.target) return;
				
				const { scrollHeight, scrollTop, clientHeight } = e.target;
				const scrollDistance = scrollHeight - scrollTop - clientHeight;
				
				if (scrollDistance < 50 && !this.loading && this.displayList.length < this.friendList.length) {
					this.loadMoreData();
				}
			},
			loadMoreData() {
				if (this.loading || this.displayList.length >= this.friendList.length) return;
				
				this.loading = true;
				const start = this.displayList.length;
				const end = start + this.pageSize;
				
				this.$nextTick(() => {
					this.displayList = [...this.displayList, ...this.friendList.slice(start, end)];
					this.loading = false;
				});
			},
			onShowAddFriend() {
				this.showAddFriend = true;
			},
			onCloseAddFriend() {
				this.showAddFriend = false;
			},
			onActiveItem(friend, idx) {
				this.$store.commit("activeFriend", idx);
				this.activeIdx = idx
				this.loadUserInfo(friend, idx);
			},
			onDelItem(friend, idx) {
				// 安全检查：确保friend对象存在且有必要的属性
				if (!friend || !friend.id || !friend.nickName) {
					this.$message.error('无效的好友信息');
					return;
				}
				
				this.$confirm(`确认删除'${friend.nickName}',并清空聊天记录吗?`, '确认解除?', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 显示加载状态
					const loading = this.$loading({
						lock: true,
						text: '正在删除...',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					});
					
					this.$http({
						url: `/friend/delete/${friend.id}`,
						method: 'delete'
					}).then((data) => {
						this.$message.success("删除好友成功");
						// 清空当前选中的用户信息
						if (this.userInfo && this.userInfo.id === friend.id) {
							this.userInfo = {};
							this.activeIdx = -1;
						}
						// 从store中移除好友和相关聊天
						this.$store.commit("removeFriend", idx);
						this.$store.commit("removePrivateChat", friend.id);
						// 更新显示列表
						this.displayList = this.friendList.slice(0, this.pageSize);
						// 刷新好友列表
						// this.$nextTick(() => {
						// 	this.loadFriendList();
						// });
						loading.close();
					}).catch(error => {
						loading.close();
						console.error('删除好友失败:', error);
						this.$message.error('删除好友失败，请重试');
					});
				}).catch(() => {
					// 用户取消删除操作
				});
			},
			// 添加好友
			onAddFriend(user) {
				this.$http({
					url: "/friend/add",
					method: "post",
					params: {
						friendId: user.id
					}
				}).then((data) => {
					this.$message.success("添加成功，对方已成为您的好友");
					let friend = {
						id: user.id,
						nickName: user.nickName,
						headImage: user.headImage,
						online: user.online
					}
					this.$store.commit("addFriend", friend);
				})
			},
			// 发送消息
			onSendMessage(user) {
				let chat = {
					type: 'PRIVATE',
					targetId: user.id,
					showName: user.userName||user.nickName,
					headImage: user.headImage
				};
				// 先打开聊天
				this.$store.commit("openChat", chat);
				// 确保聊天保存到本地存储
				this.$store.commit("saveToStorage");
				// 设置活动聊天
				this.$store.commit("getactiveChat", user.id);
				// 最后再跳转路由
				this.$nextTick(() => {
					this.$router.push("/home/chat");
				});
			},
			// 显示头像
			showFullImage() {
				if (this.userInfo.headImage) {
					this.$store.commit('showFullImageBox', this.userInfo.headImage);
				}
			},
			updateFriendInfo(friend, user, index) {
				// 只复制需要的属性，避免循环引用
				const updatedFriend = {
					id: friend.id,
					headImage: user.headImage,
					nickName: user.nickName,
					userName: friend.userName,
					remarkName: friend.remarkName,
					online: friend.online,
					onlineWeb: friend.onlineWeb,
					onlineApp: friend.onlineApp
				};
				
				this.$http({
					url: "/friend/update",
					method: "put",
					data: updatedFriend
				}).then(() => {
					this.$store.commit("updateFriend", updatedFriend);
					this.$store.commit("updateChatFromFriend", {
						id: user.id,
						headImage: user.headImage,
						nickName: user.nickName
					});
				})
			},
			loadUserInfo(friend, index) {
				this.$http({
					url: `/user/find/${friend.id}`,
					method: 'get'
				}).then((user) => {
					this.userInfo = user;
					this.remarkName = friend.remarkName || '';
					// 如果发现好友的头像和昵称改了，进行更新
					if (user.headImage != friend.headImage ||
						user.nickName != friend.nickName) {
						this.updateFriendInfo(friend, user, index)
					}
				})
			},
			startEdit() {
				this.isEditing = true;
				this.editingRemarkName = this.remarkName;
				this.$nextTick(() => {
					this.$el.querySelector('.el-input__inner').focus();
				});
			},
			cancelEdit() {
				this.isEditing = false;
				this.editingRemarkName = this.remarkName;
			},
			saveRemarkName() {
				if (!this.editingRemarkName.trim()) {
					this.$message.warning('备注名不能为空');
					return;
				}
				
				if (this.editingRemarkName === this.remarkName) {
					this.isEditing = false;
					return;
				}
				let data = {
					remark: this.editingRemarkName.trim(),
					friendId: this.userInfo.id
				}
				this.$http({
					url: "/friend/setting",
					method: 'POST',
					data: data
				}).then(() => {
					// 更新本地显示
					this.remarkName = this.editingRemarkName.trim();
					this.userInfo.userName = this.editingRemarkName.trim();
					
					// 更新 store 中的数据
					// const updatedFriend = {
					// 	...this.friendStore.activeFriend,
					// 	remarkName: this.editingRemarkName.trim()
					// };
					//this.$store.commit("updateFriend", updatedFriend);
					this.$store.dispatch('loadFriend').then(() => {
						this.$emit('refresh-friend-list');
					}).catch(err => {
						console.error('刷新好友列表失败:', err);
					});
					
					
					this.isEditing = false;
					this.$message.success('备注修改成功');
				}).catch(() => {
					this.$message.error('修改失败，请重试');
				});
			},
			refreshFriendList() {
				// 清空当前选中的用户信息
				if (this.userInfo) {
					this.userInfo = {};
					this.activeIdx = -1;
				}
				// 重新加载显示列表
				this.displayList = this.friendList.slice(0, this.pageSize);
			},
			loadFriendList() {
				// 先设置加载中状态
				this.initialLoading = true;
				// 成功后更新显示列表
				this.displayList = this.friendList.slice(0, this.pageSize);
				this.initialLoading = false;
				// 从服务器获取最新的好友列表
				// this.$store.dispatch("loadFriend").then(() => {
					
				// }).catch(error => {
				// 	console.error('加载好友列表失败:', error);
				// 	this.$message.error('加载好友列表失败，请重试');
				// 	this.initialLoading = false;
					
				// 	// 尽管发生错误，仍尝试从本地store显示数据
				// 	this.displayList = this.friendList.slice(0, this.pageSize);
				// });
			}
		},
		computed: {
			friendList() {
				return this.$store.state.friendStore.friends;
			},
			friendStore() {
				return this.$store.state.friendStore;
			},
			isFriend() {
				return this.friendStore.friends.find((f) => f.id == this.userInfo.id);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.friend-page {
		height: 100%;
		display: flex;
		overflow: hidden;
		
		.remark-wrapper {
			position: relative;
			display: flex;
			align-items: center;
			gap: 8px;
			
			.edit-icon {
				cursor: pointer;
				color: var(--el-text-color-secondary);
				font-size: 16px;
				transition: all 0.3s ease;
				
				&:hover {
					color: var(--el-color-primary);
					transform: scale(1.1);
				}
			}
		}
		
		.friend-list-box {
			background-color: #f9fafc;
			border-right: 1px solid #ebeef5;
			display: flex;
			flex-direction: column;
			height: 100%;
			position: relative;
			transition: all 0.3s;

			.friend-list-header {
				padding: 16px;
				border-bottom: 1px solid #ebeef5;
				background-color: #fff;
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
				z-index: 10;
				position: relative;
				
				.search-container {
					display: flex;
					align-items: center;
					gap: 12px;
					
					.search-input {
						flex: 1;
						
						:deep(.el-input__wrapper) {
							border-radius: 20px;
							box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
							transition: all 0.3s ease;
							
							&:hover, &:focus {
								box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
							}
							
							.el-input__prefix-inner {
								color: #909399;
							}
						}
					}
					
					.add-friend-btn {
						min-width: auto;
						font-size: 14px;
						box-shadow: 0 2px 8px rgba(var(--el-color-primary-rgb), 0.35);
						transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
						
						&:hover {
							transform: translateY(-2px);
							box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.5);
						}
					}
				}
			}

			.friend-list-items {
				flex: 1;
				overflow-y: auto;
				padding: 8px;
				
				.friend-list-container {
					padding: 5px 0;
					
					.friend-item-wrapper {
						margin-bottom: 8px;
						transition: transform 0.2s ease;
						
						&:hover {
							transform: translateY(-2px);
						}
					}
				}
				
				.loading-more {
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 15px 0;
					color: var(--el-text-color-secondary);
					font-size: 14px;
					gap: 8px;
					
					.loading-icon {
						animation: rotating 2s linear infinite;
					}
				}
				
				@keyframes rotating {
					0% {
						transform: rotate(0deg);
					}
					100% {
						transform: rotate(360deg);
					}
				}
				
				.empty-tip {
					padding: 32px 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					color: #909399;
					font-size: 14px;
				}
				
				.el-loading-mask {
					background-color: rgba(255, 255, 255, 0.7);
					
					.el-loading-spinner {
						.el-loading-text {
							color: #606266;
							margin-top: 8px;
						}
						
						.circular {
							width: 30px;
							height: 30px;
						}
					}
				}
			}
		}

		.friend-box {
			display: flex;
			flex-direction: column;	
			flex: 1;
			background-color: #fff;

			.friend-header {
				height: 60px;
				line-height: 60px;
				font-size: 18px;
				font-weight: 600;
				text-align: center;
				background-color: white;
				border-bottom: 1px solid #ebeef5;
				box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
			}

			.friend-detail {
				display: flex;
				padding: 30px;
				background-color: #fff;
				
				.info-container {
					flex: 1;
					margin-left: 30px;
					
					.friend-title {
						display: flex;
						align-items: center;
						padding: 0 0 10px 10px;
						
						.nickname {
							font-size: 18px;
							font-weight: 600;
							margin-right: 10px;
						}
					}
					
					.el-descriptions {
						padding: 20px;
						border-radius: 8px;
						box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
					}
				}
				
				.friend-btn-group {
					margin-top: 20px;
					padding: 0 20px;
					
					.el-button {
						margin-right: 15px;
						padding: 10px 20px;
						transition: all 0.3s ease;
						
						&:hover {
							transform: translateY(-2px);
							box-shadow: 0 6px 16px rgba(var(--el-color-primary-rgb), 0.3);
						}
						
						.el-icon {
							margin-right: 5px;
						}
					}
				}
			}
		}
	}
</style>